import gameConfig from "../../../configs/gameConfig";
import miniApp, {
    analyticsBase,
    authorizeParams,
    gameRecorderStartParams,
    getUserInfoParams,
    loadParams,
    loginParams, SHARE_VIDEO_SORT_TYPE, ShareVideoRankDetail,
    toastParams
} from "../miniApp";
import O1HD from "../../../gameEngine";
import { dataField } from "../dataField";

export interface ksRewardedVideoAdParam {
    // 名称	数据类型	属性	默认值	描述
    adUnitId: string;		//required	广告位 id
}

export interface ksVideoAd {
    // 通过 load 方法主动预加载广告内容。
    // 此外，在显示广告出现问题时也可以尝试主动 load 一次。
    // 该方法返回一个 Promise，如果广告已经自动拉取成功，调用该方法返回一个 resolved Promise；
    load: () => Promise<any>;
    // 广告创建后默认是隐藏的，可以通过该方法显示广告。 该方法返回一个 Promise 对象。当广告组件正常获取素材时，该 Promise 对象会是一个 resolved Promise。当广告组件发生错误时，会是一个 rejected Promise，参数与error事件监听器获得的参数相同。
    show: () => Promise<any>;
    //绑定 load 事件的监听器，用户在手动调用 load 方法后，广告组件会预先加载。 广告组件成功拉取广告素材时会触发load事件的监听器。
    //确保监听此事件时，开发者主动调用过 load 方法。
    onLoad: (listener: Function) => void;
    // 解除绑定 load 事件的监听器。
    offLoad: (listener: Function) => void;
    //绑定 error 事件的监听器。 广告组件拉取广告素材和其他情况下如果发生错误，会触发error事件的监听器。监听器会获得一个包含errCode和errMsg属性的对象参数。
    //     errCode 详情
    onError: (listener: (error: any) => void) => void;
    //    解除绑定 error 事件的监听器。
    offError: (listener: Function) => void;
    //    绑定 close 事件的监听器。 当用户点击了 Video 广告上的关闭按钮时，会触发close事件的监听器。监听器会获得一个包含isEnded属性的对象参数，表征用户是否完整观看了视频。
    onClose: (listener: (res: { isEnded: boolean }) => void) => void;
    //解除绑定 close 事件的监听器。
    offClose: (listener: Function) => void;
    onReward: (listenter: Function) => void;

    //
    destroy();
}

const ks = window["ks"];

export default class ksApi extends miniApp {
    getSystemInfoSync() {
        throw new Error("Method not implemented.");
    }
    WidgetfullScreen(): Promise<void> {
        return;
    }
    navigateToMiniGame(appId: string, successCallback?: () => void, failCallback?: () => void): void {
        console.error("#501025 未实现跳转方法");
    }

    async commitRank(rankId: dataField.RANK_ID, score: number): Promise<boolean> {
        return Promise.resolve(false);
    }

    async showRank(rankId: dataField.RANK_ID): Promise<boolean> {
        return Promise.resolve(false);
    }

    showModal(params): void {
    }

    LocalInBlockCityList(): boolean {
        return false;
    }

    vibrate(type): void {
    }


    protected m_appId: string = 'ks675821421613799990';
    protected m_secret: string = '820c32c3a9fff4c7b2db1720e30192132e5e2f07';
    protected m_adUnitId: string = '2300003608_01';

    //录屏管理器
    private m_gameRecorderManager: any = null;
    //录屏文件保存完地址
    private m_gameRecordVideoUrl: number | number[] = null;
    //视频广告组件
    private m_videoAd: ksVideoAd = null;

    private canShare: boolean = true;

    private Init() {
        console.log("Init   start");
        // ks.init({ "appId": this.m_appId });

        // this.m_gameRecorderManager = ks.createMediaRecorder(); //-old
        this.m_gameRecorderManager = ks.getGameRecorder();
        if (this.m_gameRecorderManager === null) {
            console.log("当前版本 App 不支持录屏");
        }
        console.log("Init   over");
    }

    private Read() {
        // ks.readyGo();
        console.log("Read   over");
    }

    LoadSubPackageLoadSubPack(packName: string, onComplete: (...pram: any) => void) {
        //let launchScene = "subRes"; //您的子包名称
        // var subpackageSupport = ks.isSupport(ks.Support.features.Subpackage);
        // if (!subpackageSupport) {
        //     //旧版本APP不支持，加载子包路径中的main.js即可，该路径与开发时设置的子包路径一致，如子包为sence2，路径为sence2/main.js
        //     window["require"]("subRes/main.js");
        //     onComplete && onComplete(false, "subRes");
        //     //执行你需要的逻辑，如加载场景
        //     return;
        // }

        let loadTask = ks.loadSubpackage({
            name: packName,
            success: function (res) {
                onComplete(false, res)
                console.log("分包加载成功");
                //执行你需要的逻辑，如加载场景
            }, fail: function (err) {
                onComplete(err, null);
                console.log(JSON.stringify(err));
            }
        });

        loadTask.onProgressUpdate(res => {
            console.log(res);
        });
    }

    getUserInfo(params: getUserInfoParams): void {
        //ks.getUserInfo(params);
    }

    showToast(params: toastParams): void {
        ///ks.showToast(params);
    }

    showLoading(params: loadParams): void {
        //ks.showLoading(params);
    }

    hideLoading(): void {
        //ks.hideLoading();
    }

    preCreateUnits(): void {
        this.Init();
        this.Read();
        this.createRewardedVideoAd({ adUnitId: this.m_adUnitId });
        this.m_gameRecorderManager = ks.getGameRecorder();
    }

    loadAndShowVideoAd(successCallback: () => void, errorCallback: (error: any) => void, completeCallback?: () => void): void {
        if (this.m_videoAd == null) {
            console.error('快手广告视频组件不存在');
            errorCallback(null);
            return;
        }

        this.m_videoAd.show()
            .then(() => {
                console.log("激励视频播放成功");
            });

        let onError = (err) => {
            errorCallback && errorCallback(err);
            console.log("激励视频播放失败: " + JSON.stringify(err));
        }

        this.m_videoAd.onError(onError);

        let onClose = (res) => {
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                successCallback && successCallback();
                console.log("激励视频奖励回调: " + JSON.stringify(res));
            }
            else {
                // 播放中途退出，不下发游戏奖励
                console.log("激励视频关闭回调: " + JSON.stringify(res));
            }
            this.m_videoAd.offClose(onClose);
            this.m_videoAd.offError(onError);
            completeCallback && completeCallback();
        }

        this.m_videoAd.onClose(onClose);

        //-old

        // //
        // this.m_videoAd.show({
        //     success: () => {
        //         console.log("激励视频播放成功");
        //     },
        //     fail: (result) => {
        //         errorCallback && errorCallback(result);
        //         console.log("激励视频播放失败: " + JSON.stringify(result));
        //     }
        // });
        // this.m_videoAd.onClose((result) => {
        //     completeCallback && completeCallback();
        //     //console.log("激励视频关闭回调: " + JSON.stringify(result));
        // });
        // this.m_videoAd.onReward((result) => {
        //     successCallback && successCallback();
        //     console.log("激励视频奖励回调: " + JSON.stringify(result));
        // });
    }

    login(params: loginParams): void {
        ks.login(params);
    }

    authorize(params: authorizeParams): void {
        params.success && params.success();
    }


    private m_gameRecordTimeNow: number = 0;

    gameRecordStart(params: gameRecorderStartParams, onStart?: (res) => void): void {
        //if (!this.isHaveShareVideo()) return;
        this.m_gameRecordTimeNow = Date.now();
        this.m_gameRecordVideoUrl = null;
        this.m_gameRecorderManager.on("start", (res) => {
            console.log('ks 录屏开始', res);
            onStart && onStart(res);
        });
        this.m_gameRecorderManager.on("stop", (res: any) => {
            console.log('ks 录屏结束', res.videoID);
            this.m_gameRecordVideoUrl = res.videoID;

        });
        this.m_gameRecorderManager.on("error", (res: any) => {
            console.log('ks 录屏错误 :', res.code, "-", res.msg);
        });
        this.m_gameRecorderManager.start();
    }

    gameRecordStop(): boolean {
        //if (!this.isHaveShareVideo()) return;
        // if (Date.now() - this.m_gameRecordTimeNow < 3500) {
        //     return;
        // }
        this.canShare = true;
        this.m_gameRecorderManager.stop();
        return true;
    }

    shareGameRecordVideo(successCb?: () => void, failCb?: (e?) => void): void {
        if (!this.isHaveShareVideo()) {
            O1HD.getModules().uiControlModule.showMessageBox("不能重复分享");
            return;
        }
        /****注意：没有videoID时不可展示分享录屏按钮，审核会过此case****/
        /****测试方法：点击右上角"..."按钮打开设置页面，关闭录屏开关，录屏不会产生videoID****/
        if (this.m_gameRecordVideoUrl == null) {
            O1HD.getModules().uiControlModule.showMessageBox("录屏失败，不能分享");
            return;
        }
        this.m_gameRecorderManager.publishVideo({
            video: this.m_gameRecordVideoUrl,
            callback: (error) => {
                if (error != null && error != undefined) {
                    console.log("分享录屏失败: " + JSON.stringify(error), error.code);
                    switch (error.code) {
                        case 0:
                        case -10018:
                            O1HD.getModules().uiControlModule.showMessageBox("用户取消录屏");
                            break;
                        default:
                            failCb && failCb();
                            break;
                    }
                    return;
                }
                this.canShare = false;
                console.log("分享录屏成功");
                successCb && successCb();
            }
        });
        // -old
        // this.m_gameRecorderManager.publishVideo({
        //     callback: (error) => {
        //         if (error != null && error != undefined) {
        //             console.log("分享录屏失败: " + JSON.stringify(error), error.code);
        //             switch (error.code) {
        //                 case 0:
        //                 case -10018:
        //                     O1HD.getModules().uiControlModule.showMessageBox("用户取消录屏");
        //                     break;
        //                 default:
        //                     failCb && failCb();
        //                     break;
        //             }
        //             return;
        //         }
        //         this.canShare = false;
        //         console.log("分享录屏成功");
        //         successCb && successCb();
        //     }
        // });
    }

    /**production    线上版
     development    测试版
     preview    预览版
     * */
    isProduction(): boolean {
        return ks.env.VERSION == 'production';
    }

    isHaveShareVideo(): boolean {
        return this.canShare;
    }

    //判断是否合法APP-ID
    validAppId(): void {
        // ks.onShow((res: { query, refererInfo: { appId: string, extraData: {} } }) => {
        //     if (res.refererInfo.appId != this.m_appId) {
        //         cc.game.end();
        //         throw '非法盗用此程序将受到法律制裁';
        //     } else {
        //         console.log('ks APP-ID 授权成功');
        //     }
        // });
    }

    reportAnalytics(EventKey: string, data: any): void {
        return;
        console.log("ks 发送埋点", EventKey, JSON.stringify(data))
        ks.reportAnalytics(EventKey, data);
        // console.log('ks 发送埋点', analytics.getKey(), analytics.getObj());
        // ks.reportAnalytics(analytics.getKey(), analytics.getObj());
        // ks.reportAnalytics('lookVideo', {
        //     src: 'set_value',
        // });
    }

    clearMemory(): void {

    }

    shareAppMessage(args: any): void {
    }

    protected createRewardedVideoAd(param: ksRewardedVideoAdParam) {
        this.m_videoAd = ks.createRewardedVideoAd(param);
    }

    PlayLastRecordSound(scale?: number, successCb?: () => void, errorCb?: () => void): void {
    }

    StartRecordSound(): void {
    }

    StopRecordSound(successCallback?: () => void): void {
    }

    addShortcut(): Promise<boolean> {
        return Promise.resolve(undefined);
    }

    createMoreGameBtn(): void {
    }

    drawUrlImage(url: string, overCb: (spf: cc.SpriteFrame) => void): void {
    }

    getShareVideoRank(sortType: SHARE_VIDEO_SORT_TYPE, successCb: (data: ShareVideoRankDetail[]) => void): void {
    }

    hideBanner(): void {
    }

    operateGameLive(): void {
    }

    reportAdClickNativeAd(): void {
    }

    showAddFavoriteGuide(successCallback?: () => void, failCallback?: () => void, completeCallback?: () => void): void {
    }

    showBannerAD(node: cc.Node, successCallback?: () => void, errorCallback?: (error: any) => void, onCloseCallBack?: () => void, setBannerPosition?: ({ screenWidth, screenHeight }: { screenWidth: any; screenHeight: any }) => cc.Vec2): void {
    }

    showInterstitialAd(onAdClose: () => void, onFailed: () => void): void {
    }

    showNativeAd(successCallback: (a: Array<any>) => void, errorCallback: (error: any) => void, completeCallback?: () => void): void {
    }

    showVideo(videoUrl: string): void {
    }

    subscribeMessage(successCallback?: () => void, failCallback?: () => void, completeCallback?: () => void): void {
    }

    drawHead(headUrl: string): Promise<cc.SpriteFrame> {
        return Promise.resolve(undefined);
    }

    fullScreenVideo(): Promise<void> {
        return Promise.resolve(undefined);
    }
}